import numpy as np
import cv2 as cv


def main():
    # 读入图像
    img1 = cv.imread('123.png', cv.IMREAD_GRAYSCALE)
    img2 = cv.imread('123.png', cv.IMREAD_GRAYSCALE)

    # 分别在两幅图像中提取SIFT特征
    sift = cv.SIFT.create()
    kp1, des1 = sift.detectAndCompute(img1, None)
    kp2, des2 = sift.detectAndCompute(img2, None)

    # 进行特征匹配，只保留最好的两个匹配结果
    bf = cv.BFMatcher()
    matches = bf.knnMatch(des1, des2, k = 2)

    # 绘制匹配的特征并显示
    good_matches = []
    ratio_thresh = 0.75
    for m, n in matches:
        if m.distance < ratio_thresh * n.distance:
            good_matches.append([m])
    img3 = cv.drawMatchesKnn(img1, kp1, img2, kp2, good_matches, None,
           flags = cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

    cv.imshow('Good Matches', img3)
    cv.waitKey()
    cv.destroyAllWindows()


if __name__ == '__main__':
    main()